<template>
	<view class="content">
		<image class="logo" src="/static/logo.png"></image>
		<view class="text-area">

			<button @click="sendSse">发送sse</button>
			<!-- #ifdef APP -->
			<view ref="renderJS" v-show="false">
				<button :props='senApp' :change:props='renderJS.renderBeforeSend'>app端的发送</button>
			</view>
			
			<!-- #endif -->
		</view>
		<view class="">
			{{ msg }}
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				msg: '',
				senApp:false
			}
		},
		onLoad() {

		},
		methods: {
			sendSse() {
				this.senApp = true
				// 条件编译：仅在 H5 平台中执行
				// #ifdef H5
				// 创建EventSource对象，连接到服务器端SSE接口
				const eventSource = new EventSource('http://localhost:3000/sse');
				// 监听服务器发送的消息
				eventSource.onmessage = (event) => {
					// 将接收到的消息更新到msg变量中
					this.msg += event.data;
				};
				// 监听错误事件
				eventSource.onerror = (error) => {
					console.error('SSE error:', error);
					eventSource.close(); // 关闭连接
				};
				// #endif
				// #ifdef MP-WEIXIN
				let requestTask = uni.request({
					url: 'http://localhost:3000/sse',
					enableChunked: true,
					method: 'GET',
					success(res) {
						console.log('连接关闭', res);
					}
				})

				requestTask.onHeadersReceived(res => {
					console.log('连接成功', res);
				})

				requestTask.onChunkReceived(res => {
					const arrayBuffer = res.data;
					const uint8Array = new Uint8Array(arrayBuffer);
					let data = uni.arrayBufferToBase64(uint8Array);
					data = new Buffer(data, 'base64');
					data = data.toString('utf8');
					console.log('解析', data);
					this.msg += data;
				})
				// #endif
 
			},
			//接收render传递过来的值
			emits(val) {
				console.log('收到数据',val);
				this.msg += val;
			},
			handleSSE(){
				console.log('发送sse');
			}
		}
	}
</script>
<script module='renderJS' lang='renderjs'> 
	import {
		fetchEventSource
	} from '@microsoft/fetch-event-source';
	export default {
		methods: {
			renderBeforeSend( val ){
				console.log('发送app请求',val);
				if(val){
					this.sendAppSSE()
				}
			},
			sendAppSSE(){
				let that = this;
				let str  =''
				console.log('发送请求');
				const headers = {
					'Content-Type': 'application/json',
				}
				fetchEventSource('http://192.168.54.92:3000/sse',{
					method:'get', 
					headers,
					onopen() {
						console.log('sse连接成功');
					},
					onmessage( msg ){
						let { data } = msg;
						str= data
						that.$ownerInstance.callMethod('emits',str );
					},   
					onclose(){ 
						console.log('关闭');
					}
				})
			}
		}
	}
</script>


<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>